package Conexao;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.HashMap;

import negocio.Requisicao;
import negocio.StatusConexao;

import dados.Usuario;

import Exceptions.ConnectionFailedException;
import Protocolo.MiniTCP;

;

public class ChecagemConexaoRequestEspecial implements Runnable{


	private Socket socket;
	private Socket socketPrincipal;
	private StatusConexao statusConexao;
	private HashMap<InetAddress, MiniTCP> hash;
	private Usuario usuario;

	public ChecagemConexaoRequestEspecial(Socket socket,Socket socketPrincipal, StatusConexao statusConexao,HashMap<InetAddress, MiniTCP> hash, Usuario usuario){

		this.socket=socket;
		this.socketPrincipal=socketPrincipal;
		this.statusConexao=statusConexao;
		this.hash=hash;
		this.usuario=usuario;
	}

	public void run() throws RuntimeException{

		try{

			while(!socketPrincipal.isClosed()){

				ObjectOutputStream out= new ObjectOutputStream(socket.getOutputStream()); 

				ObjectInputStream in= new ObjectInputStream(socket.getInputStream());

				Requisicao requisicao= new Requisicao(null, null, 1);

				out.writeUnshared(requisicao);

				socket.setSoTimeout(5000);

				in.readUnshared();

			}
			socket.close();

		}catch(Exception e){
			//e.printStackTrace();
		} finally {

			this.statusConexao.isConnected=false;

			MiniTCP miniTCP = hash.remove(socketPrincipal.getInetAddress());

			if (miniTCP != null) {
				try {
					miniTCP.finish();
					usuario.setConectado(false);
					System.out.println(miniTCP.getConnected());

					System.out.println( "finalizando o TCP ");
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					//e1.printStackTrace();
				} catch (ConnectionFailedException e1) {
					// TODO Auto-generated catch block
					//e1.printStackTrace();
				}
			}
		}
	}
}
